<template>
  <section>
    <el-dialog v-model="visible" :before-close="onClose" :close-on-click-modal="false"
      :title="type == 'add' ? '新增' : '编辑'" append-to-body width="800px">
      <el-form ref="formRef" :inline="false" :model="dataForm" :rules="rules" label-width="180px">
        <el-form-item label="公司" prop="companyCode">
          <SelectSearch v-model="dataForm.companyCode" :disabled="type != 'add'" style="width:100%"
            :info="COMP_SEARCH_CONF" :value="dataForm.companyCode" @on-selectListData="onCompSele"></SelectSearch>
        </el-form-item>
        <el-form-item label="部门" prop="orgCode">
          <el-cascader ref="depCascader" v-model="dataForm.orgCode" style="width:100%"
            :disabled="type != 'add' || !dataForm.companyCode" :options="orgOptions" :props="cascaderProps" clearable
            placeholder="请选择部门" @change="onDepChange" @visible-change="cascaderVisibleChange" />
        </el-form-item>
        <el-form-item label="默认预算成本中心" prop="budgetCostCenterCode">
          <el-select v-model="dataForm.budgetCostCenterCode" :disabled="!dataForm.companyCode" :loading="budgetLoading"
            :remote-method="getBudgetData" clearable filterable placeholder="请输入成本中心编码/名称搜索" style="width:100%" remote
            reserve-keyword>
            <el-option v-for="item in budgetData" :key="item.id" :label="item.label + '[' + item.centerCode + ']'"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="默认核算成本中心" prop="checkCostCenterCode">
          <el-select v-model="dataForm.checkCostCenterCode" :disabled="!dataForm.companyCode" :loading="checkLoading"
            :remote-method="getCheckData" clearable filterable placeholder="请输入成本中心编码/名称搜索" style="width:100%" remote
            reserve-keyword>
            <el-option v-for="item in checkData" :key="item.id" :label="item.label + '[' + item.centerCode + ']'"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="公司外可用预算成本中心" prop="outerBudgetCostCenterId">
          <el-select v-model="dataForm.outerBudgetCostCenterId" :loading="outBugetLoading" multiple
            @change="outBudgetChange" @visible-change="onOutVisibleChange" :remote-method="getOutBudgetData" clearable
            filterable placeholder="请输入成本中心编码/名称搜索" style="width:100%" remote reserve-keyword>
            <el-option v-for="item in budgetOptions" :key="item.id" :label="item.label + '[' + item.centerCode + ']'"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onClose">取消</el-button>
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </section>
</template>

<script>
import api from "@/api/index";
import { ElMessage } from 'element-plus'
import { computed, onMounted, reactive, toRefs, watch, watchEffect } from 'vue';
import { COMP_SEARCH_CONF } from "@/views/depCostCenterConfig/config";
import SelectSearch from '@/components/SelectSearch/index.vue'

export default {
  components: {
    SelectSearch
  },
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    type: {
      default: 'add',
      type: String
    },
    dataForm: {
      type: Object,
      default: () => {
      }
    }
  },
  emits: ['on-update', 'handleClose', 'on-close'],
  setup (props, context) {
    const state = reactive({
      formRef: null,
      depCascader: null,
      rules: {
        companyCode: [{ required: true, message: '请选择公司', trigger: 'change' }],
        orgCode: [{ type: 'array', required: true, message: '请选择部门', trigger: 'change' }],
      },
      COMP_SEARCH_CONF,
      cascaderProps: {
        checkStrictly: true,
        label: 'label',
        value: 'value',
        emitPath: false,
        lazy: true,
        multiple: true,
        lazyLoad (node, resolve) {
          let params = { parentId: node.value || props.dataForm.companyCode }
          methods.loadDepartment(params).then(res => {
            resolve(res)
          })
        }
      },
      orgData: [],
      orgTempData: props.dataForm.orgCode ? [
        {
          id: '_1',
          value: props.dataForm.orgCode,
          label: props.dataForm.orgName,
        }
      ] : [],
      compData: [],
      budgetData: [],
      checkData: [],
      outBudgetData: [], // 公司外可用预算成本中心
      budgetLoading: false,
      checkLoading: false,
      outBugetLoading: false,
      orgVisible: false,
      orgChanged: false,
      defaultOutBudgetData: (props.dataForm.outerBudgetCostCenters || []).map(item => {
        return {
          id: item.outerBudgetCostCenterId,
          label: item.outerBudgetCostCenterName,
          value: item.outerBudgetCostCenterCode,
          centerCode: item.outerBudgetCostCenterCode
        }
      }), // 编辑时回显值
      outBudgetVisible: false,
      outBudgetChange: false,
    })
    const visible = ref(false)
    const orgOptions = computed(() => {
      if (state.orgVisible || state.orgChanged) {
        return state.orgData;
      }


      return state.orgTempData
    })

    const budgetOptions = computed(() => {
      if (state.outBudgetVisible || state.outBudgetChange) {
        return state.outBudgetData;
      }


      return state.defaultOutBudgetData
    })

    const methods = {
      // 异步获取部门树
      loadDepartment (params) {
        return new Promise(resolve => {
          api.user.getDepartmentTree(params).then(res => {
            resolve(res)
          })
        })
      },
      getBudgetData (query) {
        if (!props.dataForm.companyCode) return
        let params = {
          orgCode: props.dataForm.companyCode,
          codeOrName: query
        }
        state.budgetLoading = true
        api.costCenter.budgetCostCenterList(params).then(res => {
          state.budgetData = res.list
          state.budgetLoading = false
        }).catch(() => {
          state.budgetLoading = false
        })
      },
      getCheckData (query) {
        if (!props.dataForm.companyCode) return
        let params = {
          orgCode: props.dataForm.companyCode,
          codeOrName: query
        }
        state.checkLoading = true
        api.costCenter.checkCostCenterList(params).then(res => {
          state.checkData = res.list
          state.checkLoading = false
        }).catch(() => {
          state.checkLoading = false
        })
      },
      getOutBudgetData(query) {
        let params = {
          codeOrName: query
        }
        state.outBugetLoading = true
        api.costCenter.budgetCostCenterList(params).then(res => {
          state.outBudgetData = res.list
          state.outBugetLoading = false
        }).catch(() => {
          state.outBugetLoading = false
        })
      }
    }



    const handler = {
      cascaderVisibleChange (visible) {
        state.orgVisible = visible
      },
      onDepChange (val) {
        // if (val) {
        //   props.dataForm.orgName = state.depCascader.getCheckedNodes()[0].pathLabels.join('-')
        // }
        state.orgChanged = true
      },
      onCompSele (list) {
        state.compData = list
      },
      onOutBudgetChange() {
        state.outBudgetChange = true
      },
      onOutVisibleChange(visible) {
        state.outBudgetVisible = visible
      },
      // 关闭
      onClose () {
        state.formRef.resetFields()
        state.formRef.clearValidate()
        context.emit('on-close')
      },
      // 提交
      onSubmit () {
        if (!state.formRef) return
        if (!props.dataForm.id) {
          props.dataForm.companyName = state.compData.find(item => item.companyCode === props.dataForm.companyCode).companyName
        }
        let center
        let empty = {id: '', label: ''}
        center = state.budgetData.find(item => item.centerCode === props.dataForm.budgetCostCenterCode) || empty
        props.dataForm.budgetCostCenterId = center.id
        props.dataForm.budgetCostCenterName = center.label
        center = state.checkData.find(item => item.centerCode === props.dataForm.checkCostCenterCode) || empty
        props.dataForm.checkCostCenterId = center.id
        props.dataForm.checkCostCenterName = center.label

        state.formRef.validate((valid, fields) => {
          if (valid) {
            if(!props.dataForm.checkCostCenterCode && !props.dataForm.budgetCostCenterCode && props.dataForm.outerBudgetCostCenterId.length == 0) {
              return ElMessage.warning('请至少配置一种成中心')
            }

            let data = {
              budgetCostCenterId: props.dataForm.budgetCostCenterId,
              checkCostCenterId: props.dataForm.checkCostCenterId,
              outerBudgetCostCenterId: props.dataForm.outerBudgetCostCenterId,
              companyList: []
            }

            if (props.type === 'add') {
              state.depCascader.getCheckedNodes().forEach(node => {
                data.companyList.push({
                  orgCode: node.value,
                  orgName: node.label,
                  companyCode: props.dataForm.companyCode,
                  companyName: props.dataForm.companyName
                })
              })

              api.costCenter.batchCreateCostCenter(data).then(res => {
                context.emit('on-update')
                handler.onClose()
                ElMessage.success('操作成功')
              })
            } else {
              data.companyList = [
                {
                  id: props.dataForm.id,
                  orgCode: props.dataForm.orgCode[0],
                  orgName: props.dataForm.orgName,
                  companyCode: props.dataForm.companyCode,
                  companyName: props.dataForm.companyName
                }
              ]
              api.costCenter.batchEditCostCenter(data).then(res => {
                context.emit('on-update')
                handler.onClose()
                ElMessage.success('操作成功')
              })

              // let data = JSON.parse(JSON.stringify(props.dataForm))
              // data.orgCode = data.orgCode[0]

              // api.costCenter.depEditCostCenter(data).then(res => {
              //   context.emit('on-update')
              //   handler.onClose()
              //   ElMessage.success('操作成功')
              // })
            }
          } else {
            console.log('error submit!')
            return false
          }
        })
      }
    }

    methods.getBudgetData(props.dataForm.budgetCostCenterCode || '')
    methods.getCheckData(props.dataForm.checkCostCenterCode || '')
    // 外层用v-if控制，只执行一次
    if (props.dataForm.companyCode) {
      props.dataForm.outerBudgetCostCenterId = []
      props.dataForm.orgCode = [props.dataForm.orgCode]

      if(props.dataForm.outerBudgetCostCenters) {
        props.dataForm.outerBudgetCostCenterId = props.dataForm.outerBudgetCostCenters.map(item => item.outerBudgetCostCenterId)
      } else {
        methods.getOutBudgetData('')
      }
    } else {
      props.dataForm.orgCode = []
      state.budgetData = []
      state.checkData = []
      state.outBudgetData = []
      props.dataForm.outerBudgetCostCenterId = []
      methods.getOutBudgetData('')
    }
    watch(() => props.dialogVisible, (val) => {
      if (val) visible.value = val
    })
    return {
      ...toRefs(state),
      visible,
      ...methods,
      ...handler,
      orgOptions,
      budgetOptions
    }
  }
}
</script>

<style scoped></style>
